﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Styx.Helpers;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace WatchMyToon
{
    class Updater
    {
	
        private String URL = "http://watchmytoon.com/updates";
		
        private String BaseUrl = "";

        private String getInfos()
        {
            try
            {
                String ReturnString = "";
                using (WebClient client = new WebClient()) // WebClient class inherits IDisposable
                {
                    ReturnString = client.DownloadString(URL + "/updater.php");
                }

                ReturnString = ReturnString.Replace("<br>", "@");
                return ReturnString;
            }
            catch (Exception ex)
            {
                return String.Empty;
            }

        }
        static readonly Regex LinkPattern = new Regex(@"<li><a href="".+"">(?<ln>.+(?:..))</a></li>", RegexOptions.CultureInvariant);

        static string RemoveXmlEscapes(string xml)
        {
            return xml.Replace("&amp;", "&").Replace("&lt;", "<").Replace("&gt;", ">").Replace("&quot;", "\"").Replace("&apos;", "'");
        }

        private void CreatePath(String path)
        {
            Directory.CreateDirectory(path);
        }

        private Boolean getFiles(WebClient _client, String url)
        {
            try
            {
                WebClient client = _client;
                string html = client.DownloadString(url);
                MatchCollection results = LinkPattern.Matches(html);

                IEnumerable<Match> matches = from match in results.OfType<Match>() where match.Success && match.Groups["ln"].Success select match;
                foreach (Match match in matches)
                {
                    string file = RemoveXmlEscapes(match.Groups["ln"].Value);
                    string newUrl = url + file.TrimStart(' ');

                    if (newUrl.Contains("Parent Directory"))
                        continue;

                    if (newUrl[newUrl.Length - 1] == '/') // it's a directory...
                    {
                        getFiles(client, newUrl);
                    }
                    else // its a file.
                    {
                        string clientpath = getPluginPath() + newUrl.Replace(BaseUrl, "").Replace('/', '\\');
                        String directoryName = Path.GetDirectoryName(clientpath);
                        DirectoryInfo info = new DirectoryInfo(clientpath);

                        if (!Directory.Exists(directoryName))
                            CreatePath(directoryName);

                        client.DownloadFile(newUrl, directoryName + "\\" + info.Name);
                      

                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while download");
                return false;
       
            }
        }

        private String getPluginPath()
        {
            try
            {
                StringBuilder returnString = new StringBuilder();

                returnString.Append(Application.StartupPath);
                returnString.Append("\\Plugins\\");

                return returnString.ToString(); ;

            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while getPluginPath()");
                return String.Empty;
            }

        }

        private Boolean Update(String folderFrom)
        {
            BaseUrl = URL + folderFrom.Remove(0, folderFrom.IndexOf('"')).Replace("\"", "");
            return getFiles(new WebClient(), BaseUrl);

        }

        public void CheckForUpdate(Version actualversion)
        {
            try
            {

                string[] Infos = getInfos().Split('@');

                string CurrentVersion = Infos[0].Remove(0, Infos[0].IndexOf('"') - 1);
                string[] currenta = CurrentVersion.Replace("\"", "").Replace("V", "").Split('.');
                Version current = new Version(Convert.ToInt32(currenta[0]), Convert.ToInt32(currenta[1]), Convert.ToInt32(currenta[2]));

                if (current > actualversion)
                {

                    Logging.Write(Color.Purple, "[WatchMyToon] - New Version released! Start update ...");
                    if(Update(Infos[1]))
                        Logging.Write(Color.GreenYellow, "[WatchMyToon] - Update done please restart HB");
                    else
                        Logging.Write(Color.Red, "[WatchMyToon] - Error while updating skip update");

                }
                else
                {
                    Logging.Write(Color.Purple, "[WatchMyToon] - You are uptodate");
                }

            }
            catch (Exception ex)
            {
                Logging.Write(Color.Red, "[WatchMyToon] - Error while CheckForUpdate()");

            }
        }
    }
}
